﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using wp8nop.Resources;
using wp8nop.ViewModel;
using System.Windows.Media.Imaging;
using System.Diagnostics;
using GalaSoft.MvvmLight.Messaging;
using Microsoft.Practices.ServiceLocation;
using wp8nop.Model;
using wp8nop.Common;
using System.Reflection;
using Microsoft.Phone.Tasks;

namespace wp8nop
{
    public partial class MainPage : PhoneApplicationPage
    {

        MainViewModel vm;
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            
            vm = (MainViewModel) this.DataContext;
            vm.OnVetrinaLoaded += vm_OnVetrinaLoaded;
            vm.OnOpenDettaglioProdotto += vm_OnOpenDettaglioProdotto;
            this.Loaded += MainPage_Loaded;
            // Sample code to localize the ApplicationBar
            //BuildLocalizedApplicationBar();
            versione.Text = "Versione: " + GetVersion();

            this.ApplicationBar.Mode = ApplicationBarMode.Minimized;
            if (!string.IsNullOrEmpty(App.Email) && !string.IsNullOrEmpty(App.Password))
            {
                nopService.NopServiceClient client = new nopService.NopServiceClient();
                client.ValidateUserCompleted +=client_ValidateUserCompleted;
                client.ValidateUserAsync(App.Email, App.Password);
                Debug.WriteLine("mi sto loggando automaticmanete " + App.Email + " " + App.Password);

            }
        }

        public static string GetVersion()
        {
            var versionAttribute = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyFileVersionAttribute), true).FirstOrDefault() as AssemblyFileVersionAttribute;

            if (versionAttribute != null)
            {
                return versionAttribute.Version;
            }
            return "";
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {

        }

        void client_ValidateUserCompleted(object sender, nopService.ValidateUserCompletedEventArgs e)
        {
            if (e.Error != null)
                Toast.SendToast("Si è verificato un errore di comunicazione con i nostri server, provare più tardi");

            else
            {
                Debug.WriteLine("Result: " + e.Result.ToString());
                if (e.Result > 0)
                {
                    App.IDUtente = e.Result;
                    Debug.WriteLine("login automatico ok");
                }
                else
                {
                }
            }
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (vm.Vetrina != null)
                LoadProdottiVetrina(vm.Vetrina);
            
            base.OnNavigatedTo(e);
        }

        void vm_OnOpenDettaglioProdotto(object sender, ProdottoViewModel e)
        {
            OpenDettagioProdotto(e);
        }

        void vm_OnVetrinaLoaded(object sender, List<ProdottoViewModel> prodList)
        {

            LoadProdottiVetrina(prodList);
            
        }

        private void LoadProdottiVetrina(List<ProdottoViewModel> prodList)
        {
            try
            {
                if (wrapPanel.Children.Count > 0)
                    return;
                //  wrapPanel.Width = 188 * ((float) e.Count / 2.0);
                Debug.WriteLine("Items: " + prodList.Count);
                foreach (var prod in prodList)
                {
                    StackPanel b = new StackPanel()
                    {
                        Width = 190,
                        Height = 230,
                        Margin = new Thickness(8)
                    };

                    Image img = new Image();
                    img.Source = new BitmapImage(new Uri(prod.Model.imgs.thumb, UriKind.Absolute));
                    img.Width = 190;
                    img.Height = 190;


                    b.Children.Add(img);
                    TextBlock t = new TextBlock();
                    t.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
                    t.Text = prod.Price;
                    t.FontSize = 20;
                    t.Margin = new Thickness(0, 8, 0, 0);
                    b.Children.Add(t);
                    b.Tap += (s, e) =>
                    {
                        vm.OpenDettaglioProdotto(prod);
                    };

                    wrapPanel.Children.Add(b);
                }
            }
            catch (Exception ex)
            {

                Debug.WriteLine("Ecc: " + ex.Message);
            }
        }

        void OpenDettagioProdotto(ProdottoViewModel prod)
        {
            var dettProd = ServiceLocator.Current.GetInstance<DettaglioProdottoViewModel>();
            NavigationService.Navigate(new Uri("/DettaglioProdotto.xaml", UriKind.Relative));

            Debug.WriteLine("Invio messaggio");
            Messenger.Default.Send(new NotificationMessage<ProdottoViewModel>(prod, "SelectedProduct"));
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            vm.SelectedCategory = null;
            vm.SelectedProduct = null;
        }

        private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var cat = (Categoria) e.AddedItems[0];
            if (cat.IDCategoria == 0)
            {
                var dettProd = ServiceLocator.Current.GetInstance<ProdottiListViewModel>();
                dettProd.SearchString = cat.Ricerca;
                dettProd.SelectedCategory = null;
                NavigationService.Navigate(new Uri("/ProdottiList.xaml", UriKind.Relative));
            }
            else if (cat.Ricerca == "novita")
            {
                var dettProd = ServiceLocator.Current.GetInstance<ProdottiListViewModel>();
                dettProd.SearchString = null;
                dettProd.SelectedCategory = cat;
                NavigationService.Navigate(new Uri("/ProdottiList.xaml", UriKind.Relative));
            }
            else
                NavigationService.Navigate(new Uri(string.Format("/SubCategorie.xaml?id={0}&cat={1}", cat.IDCategoria, cat.Ricerca), UriKind.Relative));

        }

        private void CondVendita_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            WebBrowserTask task = new WebBrowserTask();
            task.Uri = new Uri("http://127.0.0.1/t/conditionsofUse");
            task.Show();
        }

        private void Privacy_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            WebBrowserTask task = new WebBrowserTask();
            task.Uri = new Uri("http://127.0.0.1/t/privacyinfo");
            task.Show();
        }

        private void Spedizione_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            WebBrowserTask task = new WebBrowserTask();
            task.Uri = new Uri("http://127.0.0.1/t/shippinginfo");
            task.Show();
        }

        private void Sostituzioni_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            WebBrowserTask task = new WebBrowserTask();
            task.Uri = new Uri("http://127.0.0.1/t/DeliveryInformation");
            task.Show();
        }

        private void Supporto_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            EmailComposeTask emailComposeTask = new EmailComposeTask();

            emailComposeTask.Subject = "Richiesta supporto";
            emailComposeTask.Body = "";
            emailComposeTask.To = "supporto@24carati.com";

            emailComposeTask.Show();
        }

        private void Panorama_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //if (panorama.SelectedItem == tabInfo)
            //    this.ApplicationBar.Mode = ApplicationBarMode.Default;
            //else
            //    this.ApplicationBar.Mode = ApplicationBarMode.Minimized;
        }

        private void GoCarrello_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Carrello.xaml", UriKind.Relative));
        }


        // Sample code for building a localized ApplicationBar
        //private void BuildLocalizedApplicationBar()
        //{
        //    // Set the page's ApplicationBar to a new instance of ApplicationBar.
        //    ApplicationBar = new ApplicationBar();

        //    // Create a new button and set the text value to the localized string from AppResources.
        //    ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("/Assets/AppBar/appbar.add.rest.png", UriKind.Relative));
        //    appBarButton.Text = AppResources.AppBarButtonText;
        //    ApplicationBar.Buttons.Add(appBarButton);

        //    // Create a new menu item with the localized string from AppResources.
        //    ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
        //    ApplicationBar.MenuItems.Add(appBarMenuItem);
        //}
    }
}